package ar.edu.unlp.info.tesis.security;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import ar.edu.unlp.info.tesis.database.service.GenericService;


@Service
@Transactional(readOnly = true)
public class CustomUserAccessService implements UserDetailsService {
	
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		try {
			ar.edu.unlp.info.tesis.domain.Usuario domainUser = (ar.edu.unlp.info.tesis.domain.Usuario) GenericService.getService(ar.edu.unlp.info.tesis.domain.Usuario.class).findByProperty("username", username);
			
			boolean enabled = true;
			boolean accountNonExpired = true;
			boolean credentialsNonExpired = true;
			boolean accountNonLocked = true;
			
			UserDetails u = new User(
					domainUser.getUsername(), 
					domainUser.getPassword(),
					enabled,
					accountNonExpired,
					credentialsNonExpired,
					accountNonLocked,
					getAuthorities(domainUser.getRol().getCodigo()));
			return u;
			
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	
	public Collection<? extends GrantedAuthority> getAuthorities(Integer role) {
		List<GrantedAuthority> authList = getGrantedAuthorities(getRoles(role));
		return authList;
	}
	
	public List<String> getRoles(Integer role) {
		List<String> roles = new ArrayList<String>();
		
		if (role.intValue() == 1)
		{
			roles.add("ROLE_ADMIN");
			roles.add("ROLE_APOSTADOR");
		}
		else if (role.intValue() == 2)
			roles.add("ROLE_APOSTADOR");
		
		return roles;
	}
	
	public static List<GrantedAuthority> getGrantedAuthorities(List<String> roles) {
		List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
		for (String role : roles) {
			authorities.add(new SimpleGrantedAuthority(role));
		}
		return authorities;
	}
}
